<template>
  <div>
    <el-dialog :title="title" :fullscreen=true :close-on-click-modal="false" :visible.sync="visible" @close="OnClose">
      <el-row :gutter="10">
        <el-col :span="15">
          <el-card shadow="never" :body-style="contentViewHeight" class="uni-map-panel">
            <PointAddList ref="pointAddList" :floorId='inputForm.floor.id' type="ibeacon"
              url='/smis/ibeacon/jfIbeacon/list' nameKey='mijor' @onMapClick="onMapClick" @onDataClick="onDataClick"
              @onLoadComplete="onLoadComplete" @dbClick="doSubmit()" @onBeaconList="onBeaconList"></PointAddList>
          </el-card>
        </el-col>
        <el-col :span="9">
          <el-card shadow="never" :body-style="contentViewHeight" class="uni-data-panel">
            <el-button type="text" style="float: right; margin-bottom: 20px;" v-if="hasPermission('smis:system')"
              @click="doRecordSubmit()" v-noMoreClick>上传记录</el-button>

            <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
              :disabled="method==='view'" label-width="120px">
              <el-row :gutter="15">
                <el-col :span="22">
                  <el-form-item label="标注" prop="name" :rules="[
                       ]">
                    <el-input v-model="inputForm.name" placeholder="请填写标注"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="uuid" prop="uuid" :rules="[
                        {required: true, message:'uuid不能为空', trigger:'blur'}
                       ]">
                    <el-input v-model="inputForm.uuid" placeholder="请填写uuid"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="major" prop="major" :rules="[
                        {required: true, message:'major不能为空', trigger:'blur'}
                       ]">
                    <el-input v-model="inputForm.major" placeholder="请填写major"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="mijor" prop="mijor" :rules="[
                        {required: true, message:'mijor不能为空', trigger:'blur'}
                       ]">
                    <el-input v-model="inputForm.mijor" placeholder="请填写mijor(UWB是4位16进制 EF03)"></el-input>
                    <el-checkbox v-model="autoUp" style="position: absolute; right: 5px; ">自增</el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="设备高度" prop="z" :rules="[
                        {required: true, message:'设备高度不能为空', trigger:'blur'}
                       ]">
                    <el-input v-model="inputForm.z" placeholder="设备需要填写 单位:米"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="x轴" prop="x" :rules="[
                        {required: true, message:'x轴不能为空', trigger:'blur'}
                       ]">
                    <el-input v-model="inputForm.x" placeholder="请填写x轴"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="y轴" prop="y" :rules="[
                        {required: true, message:'y轴不能为空', trigger:'blur'}
                       ]">
                    <el-input v-model="inputForm.y" placeholder="请填写y轴"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-button type="primary" @click="doSubmit()" v-noMoreClick>添加(双击选中并提交)</el-button>
            <el-button type="info" style="margin-left: 50px; margin-bottom: 10px;" v-if="hasPermission('smis:system')"
              @click="doOfflineRecord()" v-noMoreClick>离线记录</el-button>
            <div class="uni-notice" v-if="hasPermission('smis:system')">网络不好环境，可先离线记录数据，待网络通畅后上传至服务器</div>
            <div class="uni-addlist-delete" v-if="selectItem.id !== ''">
              <div>当前选中了{{selectItem.name}}</div>
              <el-button type="danger" size="small" @click="doDelete()" v-noMoreClick>删除</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import PointAddList from '@/components/jfMap/pointAddList.vue'
  export default {
    data() {
      return {
        title: '',
        method: '',
        autoUp: false,
        visible: false,
        loading: false,
        selectItem: {
          id: '',
          name: ''
        },
        inputForm: {
          id: '',
          floor: {
            id: ''
          },
          name: '',
          uuid: '500A3E07-E190-4D1F-8CC3-3F76925346C8',
          major: '10194',
          mijor: '',
          x: '',
          y: ''
        }
      }
    },
    components: {
      SelectTree,
      PointAddList
    },
    computed: {
      contentViewHeight() {
        let height = this.$store.state.common.documentClientHeight - 152
        return {
          height: height + 'px'
        }
      }
    },
    methods: {
      init(method, id, floorId) {
        this.method = method
        this.inputForm.id = id
        this.title = `批量添加`
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.inputForm.floor.id = floorId
          this.resetFields()
          this.$refs.pointAddList.resize();
          this.$refs.pointAddList.showFloor(floorId)
        })
      },
      onBeaconList(e) {
        this.$confirm('当前楼层为G1/G2格式地图, 可一键更新Beacon数据, 是否继续?', '提示', {
          confirmButtonText: '立即更新',
          cancelButtonText: '再想一想',
          type: 'warning'
        }).then(() => {
          this.updateBeaconList(e);
        }).catch(() => {

        });
      },
      updateBeaconList(e) {
        var floorData = e.floorData;
        var beaconList = e.beaconList || [];
        // console.log(beaconList);
        this.loading = true
        this.$http({
          url: `/smis/ibeacon/jfIbeacon/updateBeaconList`,
          method: 'post',
          data: {
            floorId: floorData.floorId,
            beaconListStr: JSON.stringify(beaconList)
          }
        }).then(({
          data
        }) => {
          if (data && data.success) {
            this.$message.success(data.msg)
            this.$refs.pointAddList.refreshList()
            this.resetFields()
          }
          this.loading = false
        })
      },
      resetFields() {
        this.inputForm.id = ''
        this.inputForm.name = ''
        this.inputForm.mijor = this.autoUp ? this.getAutoUpNumber(this.inputForm.mijor) : ''
        this.inputForm.x = ''
        this.inputForm.y = ''
        // this.inputForm.z = ''
      },
      getAutoUpNumber(code) {
        if (!code || code === "") {
          return ""
        }
        var list = code.split("")
        var numCode = ''
        for (var i = list.length - 1; i >= 0; i--) {
          var isnum = /^\d+$/.test(list[i]);
          if (isnum) {
            numCode = list[i] + numCode
          } else {
            break
          }
        }
        if (numCode === '') {
          return code
        }
        var prefix = code.substr(0, code.length - numCode.length)
        var newCode = (parseInt(numCode) + 1) + ''
        for (var len = newCode.length, i = 0; i < numCode.length - len; i++) {
          newCode = '0' + newCode
        }
        return prefix + newCode
      },
      // 表单提交
      doSubmit(callback) {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: `/smis/ibeacon/jfIbeacon/save`,
              method: 'post',
              data: this.inputForm
            }).then(({
              data
            }) => {
              if (data && data.success) {
                this.$message.success(data.msg)
                this.$refs.pointAddList.refreshList()
                this.resetFields()
                callback && callback()
              }
              this.loading = false
            })
          }
        })
      },
      getRecordList() {
        var recordStr = localStorage.getItem("beaconRecordList");
        if (recordStr && recordStr.length > 4) {
          return JSON.parse(recordStr);
        }
        return []
      },
      // 上传保存离线记录
      doRecordSubmit() {
        var recordList = this.getRecordList();
        if (recordList.length > 0) {
          this.inputForm = recordList.pop();
          this.$nextTick(() => {
            this.doSubmit(() => {
              this.$refs.pointAddList.removeMarkPoint(this.inputForm.name)
              localStorage.setItem("beaconRecordList", JSON.stringify(recordList))
              this.doRecordSubmit();
            });
          })
        }
      },
      // 离线记录
      doOfflineRecord() {

        this.inputForm.filesAll = JSON.stringify(this.inputForm.file)
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            var recordList = this.getRecordList();
            recordList.push(this.inputForm);
            localStorage.setItem("beaconRecordList", JSON.stringify(recordList))
            this.$message.success("已存储至缓存，当前缓存记录数：" + recordList.length + "条")
            console.log("doOfflineRecord")
            this.$refs.pointAddList.addMarkPoint(this.inputForm.mijor, this.inputForm.mijor, this.inputForm.floor
              .id, this.inputForm.x, this.inputForm.y, this.inputForm.z || 0)
            this.resetFields()
          }
        })
      },
      onLoadComplete() {
        console.log("onLoadComplete")
        setTimeout(() => {
          var recordList = this.getRecordList();
          for (var i = 0; i < recordList.length; i++) {
            this.$refs.pointAddList.addMarkPoint(recordList[i].mijor, recordList[i].mijor, recordList[i].floor.id,
              recordList[i].x, recordList[i].y, recordList[i].z || 0)
          }
        }, 100)
      },
      doDelete() {
        // 检查缓存是否存在，存在则删缓存的
        var recordList = this.getRecordList();
        for (var i = 0; i < recordList.length; i++) {
          if (recordList[i].name === this.selectItem.id) {
            this.$message.success("已删除对应缓存记录")
            this.$refs.pointAddList.removeMarkPoint(this.selectItem.id);
            this.selectItem = {
              id: '',
              name: ''
            }
            recordList.splice(i, 1);
            localStorage.setItem("beaconRecordList", JSON.stringify(recordList))
            return;
          }
        }
        this.loading = true
        this.$http({
          url: '/smis/ibeacon/jfIbeacon/delete',
          method: 'delete',
          params: {
            'ids': this.selectItem.id
          }
        }).then(({
          data
        }) => {
          if (data && data.success) {
            this.$message.success(data.msg)
            this.$refs.pointAddList.refreshList()
            this.selectItem = {
              id: '',
              name: ''
            }
          }
          this.loading = false
        })
      },
      onMapClick(e) {
        this.inputForm.x = e.x
        this.inputForm.y = e.y
      },
      onDataClick(e) {
        this.selectItem = e
      },
      OnClose() {
        this.$emit('refreshDataList')
      }
    }
  }
</script>
